<template>
  <Spin :spinning="loading1" tip="Loading...">
    <div>
      <!-- 旧件审核信息 -->
      <TopFilter ref="TopFilterss" :list="topFilterList" :collapse="collapse" :cols="3" labelWidth="90"
        @filterChange="changeHandle" @resetChange="resetHandle"></TopFilter>
      <!-- table -->
      <Spin :spinning="loading" tip="导入中，请稍后...">
        <FilterTable ref="table" :columns="columns" :params="fetchParams" :fetchapi="fetchapi" :datakey="'records'"
          :onColumnsChange="(columns) => (this.columns = columns)" :is-select-column="false"
          :onRowSelectChange="selectChange" :isColumnFilter="false">
          <template slot="controls" slot-scope="props">
            <multiuse-button size="small" type="primary" :click="exportFileBtn.bind()">导出</multiuse-button>
          </template>
        </FilterTable>
        <BaseDialog :visible.sync="visible" :title="'车型选择'" destroyOnClose
          :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
          <ModelVehicle @close="close" @save="save"></ModelVehicle>
        </BaseDialog>
        <BaseDialog :visible.sync="selectDelearFlag" :title="'服务中心选择'" destroyOnClose
          :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
          <DealerList @close="Delearclose" @save="Delearsave" />
        </BaseDialog>
      </Spin>
    </div>
  </Spin>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
import ModelVehicle from '@/pages/claimDemage/tools/ModelVehicle.vue';
import { exportExcelFile } from '@/utils/index';
import { getListByPage, getListForExportNew } from '@/api/usedPartsReturnManage/usedPartsReturn_OEM/usePartsAuditData';
import { getRegion, getLevelOneArea, getLevelTwoAndThreeArea } from '@/api/cms-common/dealerdata/index';
import moment from "moment";
export default {
  mixins: [dictionary],
  components: { DealerList, ModelVehicle },
  data() {
    return {
      fetchapi: getListByPage,
      topFilterList: this.topFilterInitFun(),
      columns: this.creatHeader(),
      selectDelearFlag: false,
      visible: false,
      collapse: false,
      fetchParams: {
        xhrAbort: true,
        dealerCode: null,
        //赋值开始时间在拼接时分秒
        beginDate: moment(new Date()).subtract(1, 'months')
          .format('YYYY-MM-DD').split(' ')[0] + ' 00:00:00',
        //赋值结束时间在拼接时分秒
        endDate: moment(new Date())
          .format('YYYY-MM-DD').split(' ')[0] + ' 23:59:59',
      }, //ipa 接口
      selectedRows: [], //选中经销商
      loading: false,
      loading1: false,
      dealerData: [],
      ORG_TYPE_SERVICE_WAR_AREA: 15061019, //服务战区
      ORG_TYPE_SERVICE_BIG_AREA: 15061020, //服务大区
      ORG_TYPE_SERVICE_SMALL_AREA: 15061021, //服务小区
    };
  },
  mounted() {
    this.getTopLevelArea(this.ORG_TYPE_SERVICE_WAR_AREA, 'serviceWarArea');
  },
  methods: {
    // 导出
    async exportFileBtn() {
      try {
        let params = { ...this.fetchParams }
        let res = await getListForExportNew(params);
        exportExcelFile(res.data, '旧件审核信息')
      } catch (err) {
        console.warn(err)
      }
    },
    // SelectDelear() {
    //   this.selectDelearFlag = true;
    // },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    //关闭
    Delearclose() {
      this.selectDelearFlag = false;
    },
    //服务中心选择保存
    Delearsave(obj) {
      console.log('选择数据传递', obj);
      this.dealerData = obj;
      this.selectDealerData = [];
      obj.forEach((item) => {
        this.selectDealerData.push(item.dealerCompanyCode);
        this.fetchParams.dealerCode = item.dealerCode
      });
      this.selectDelearFlag = false;
    },
    resetHandle(val) {
      this.dealerData = [];
      this.selectDealerData = [];
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCode: null }, { xhrAbort: false });
    },
    save(obj) {
      this.topFilterList.find(x => x.fieldName == 'modelName').initialValue = obj[0].modelName;
      this.visible = false;
    },
    close() {
      this.visible = false;
    },
    chooseOrderNo() {
      this.visible = true;
    },
    //搜索获取数据
    changeHandle(val) {
      val.beginDate = val.beginDate ? val.beginDate.split(' ')[0] + ' 00:00:00' : '';
      val.endDate = val.endDate ? val.endDate.split(' ')[0] + ' 23:59:59' : '';
      console.log('输出的参数', val)
      this.fetchParams = Object.assign({}, this.fetchParams, val, { xhrAbort: false });
    },
    //查询条件
    topFilterInitFun() {
      return [
        {
          type: 'SELECT',
          label: '服务中心',
          render: (p) => {
            return (
              <div>
                <el-select v-model={this.selectDealerData} disabled={true} multiple placeholder="请选择">
                  {this.dealerData.map((item) => (
                    <el-option key={item.dealerCode} label={item.dealerShortname} value={item.dealerCompanyCode} />
                  ))}
                </el-select>
                <multiuse-button style="position: absolute;right: 0;height:100%" icon="el-icon-search" onClick={() => this.selectDelearFlag = true} />
              </div>
            );
          },
          onChange: val => {
            console.log(val)
          }
        },
        {
          type: 'RANGE_DATE',
          label: '日期',
          fieldName: 'beginDate|endDate',
          placeholder: '请输入',
          initialValue: [
            moment(new Date()).subtract(1, 'months')
              .format('YYYY-MM-DD'),
            moment(new Date())
              .format('YYYY-MM-DD')],
          dateType: 'daterange',
          rules: [{ required: true, message: '请选择日期', trigger: 'blur' }],
        },
        {
          type: 'INPUT',
          label: '车型名称',
          fieldName: 'modelName',
          placeholder: '请输入',
          initialValue: '',
          unitRender: p => {
            return (
              <div>
                <multiuse-button icon="el-icon-search" onClick={() => this.chooseOrderNo()} />
              </div>
            );
          }
        },
        {
          type: 'SELECT',
          label: '服务战区',
          fieldName: 'serviceWarArea',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          change: (val) => {
            console.log('val', val)
            this.changeTopAndMiddleLevelArea(val, this.ORG_TYPE_SERVICE_BIG_AREA, 'serviceWarArea', 'serviceBigArea', 'serviceSmallArea');
          },
        },
        {
          type: 'SELECT',
          label: '服务大区',
          fieldName: 'serviceBigArea',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          change: (val) => {
            this.changeTopAndMiddleLevelArea(val, this.ORG_TYPE_SERVICE_SMALL_AREA, 'serviceBigArea', 'serviceSmallArea', 'serviceSmallArea');
          },
        },
        {
          type: 'SELECT',
          label: '服务小区',
          fieldName: 'serviceSmallArea',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
        },
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          fixed: 'left',
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        //车型，服务站区，服务大区，服务小区，年月，服务中心代码，服务中心简称，
        { title: '车型', dataIndex: 'modelName', align: 'center', sorter: true, },
        { title: '服务战区', dataIndex: 'serviceWarArea', align: 'center', sorter: true, },
        { title: '服务大区', dataIndex: 'serviceBigArea', align: 'center', sorter: true },
        { title: '服务小区', dataIndex: 'serviceSmallArea', align: 'center', sorter: true },
        { title: '年月', dataIndex: 'endDate', sorter: true, align: 'center', dateFormat: 'yyyy-MM', },
        { title: '服务中心代码', dataIndex: 'dealerCode', sorter: true, align: 'center', width: 200 },
        { title: '服务中心简称', dataIndex: 'dealerName', sorter: true, align: 'center', width: 200 },
        // {
        //   title: '常规回运数',
        //   align: 'center',
        //   children: [
        //     {
        //       title: '应返回数',
        //       align: 'center',
        //       dataIndex: 'partCount',
        //       render: (props) => {
        //       return <span>{Number(props.row.partCount)}</span>;
        //     },
        //   },
        //     {
        //       title: '实际返回数',
        //       align: 'center',
        //       dataIndex: 'finalPartCount',
        //       render: (props) => {
        //       return <span>{Number(props.row.finalPartCount)}</span>;
        //     },
        //     }
        //   ]
        // },
        // {
        //   title: '紧急回运数',
        //   align: 'center',
        //   children: [
        //     {
        //       title: '月提前返回',
        //       align: 'center',
        //       dataIndex: 'urgencyMonthPartCount',
        //       render: (props) => {
        //       return <span>{Number(props.row.urgencyMonthPartCount)}</span>;
        //     },
        //     },
        //     {
        //       title: '实际返回',
        //       align: 'center',
        //       dataIndex: 'finalUrgencyMonthPartCount',
        //       render: (props) => {
        //       return <span>{Number(props.row.finalUrgencyMonthPartCount)}</span>;
        //     }
        //   }
        //   ]
        // },
        {
          title: '应返回数',
          align: 'center',
          dataIndex: 'partCount',
          render: (props) => {
            return <span>{Number(props.row.partCount)}</span>;
          },
        },
        {
          title: '实际返回数',
          align: 'center',
          children: [
            {
              title: '常规回运',
              align: 'center',
              dataIndex: 'finalPartCount',
              render: (props) => {
                return <span>{Number(props.row.finalPartCount)}</span>;
              },
            },
            {
              title: '紧急回运',
              align: 'center',
              dataIndex: 'finalUrgencyMonthPartCount',
              render: (props) => {
                return <span>{Number(props.row.finalUrgencyMonthPartCount)}</span>;
              }
            }
          ]
        },
        {
          title: '通过数',
          align: 'center',
          children: [
            {
              title: '今日新增',
              align: 'center',
              dataIndex: 'passTodayCount',
              render: (props) => {
                return <span>{Number(props.row.passTodayCount)}</span>;
              },
            },
            {
              title: '累计',
              align: 'center',
              dataIndex: 'addPassCount',
              render: (props) => {
                return <span>{Number(props.row.addPassCount)}</span>;
              },
            }
          ]
        },
        {
          title: '拒赔数',
          align: 'center',
          children: [
            {
              title: '今日新增',
              align: 'center',
              dataIndex: 'todayClaimsRejectedCount',
              render: (props) => {
                return <span>{Number(props.row.todayClaimsRejectedCount)}</span>;
              },
            },
            {
              title: '累计',
              align: 'center',
              dataIndex: 'claimsRejectedCount',
              render: (props) => {
                return <span>{Number(props.row.claimsRejectedCount)}</span>;
              },
            }
          ]
        },
        {
          title: '拒赔率%',
          align: 'center',
          children: [
            {
              title: '月度',
              align: 'center',
              dataIndex: 'claimsRejected',
              render: (props) => {
                return <span>{Number(props.row.claimsRejected)}</span>;
              },
            },
          ]
        },
      ];
    },
    //获取大区
    async getBigArea() {
      const res = await getRegion();
      if (res.resultCode === 200) {
        this.topFilterList.find((item) => item.fieldName === 'serviceBigArea').itemList = res.data.map((x) => ({ value: parseInt(x.id), text: x.orgName }));
      }
    },
    //获取顶层组织数据
    async getTopLevelArea(areaType, filedName) {
      const res = await getLevelOneArea(areaType);
      if (res.resultCode === 200) {
        this.topFilterList.find((item) => item.fieldName === filedName).itemList = res.data.map((x) => ({ value: parseInt(x.id), text: x.orgName }));
      }
    },
    //顶层和中层组织数据修改
    async changeTopAndMiddleLevelArea(deptId, sonAreaType, parentFieldName, sonFieldName, smallFieldName, flag = true) {
      let sonArea = this.topFilterList.find((item) => item.fieldName === sonFieldName);
      let smallArea = this.topFilterList.find((item) => item.fieldName === smallFieldName);
      if (!deptId) {
        sonArea.initialValue = '';
        sonArea.itemList = [];
        smallArea.initialValue = '';
        smallArea.itemList = [];
      } else {
        if (flag) {
          //正常的级联，清空原来选择的数据
          sonArea.initialValue = '';
          smallArea.initialValue = '';
        }
        const res = await getLevelTwoAndThreeArea(sonAreaType, deptId);
        if (res.resultCode === 200) {
          sonArea.itemList = res.data.map((x) => ({ value: parseInt(x.id), text: x.orgName }));
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>

</style>
